<?// REQUIRED & INCLUDE FILESrequire($pre."includes/date_parse.php");require($pre."includes/date_conversion.php");require($pre."includes/config.inc.php");//require($pre."includes/functionsAJAX.php");
// Check for page requiring logged in usersession_start();if ($loggedUser == 1) {	if (!empty($member)) { $reDir = "login.php?member=1"; }	else { $reDir = "login.php"; }	if (empty($_SESSION['logged'])) { header("Location: $reDir"); }}

$pathInfo = pathinfo($PHP_SELF);
// Create new visitor record if one does not exist
/*$sqlCheck = "SELECT * from transVisitorStats WHERE SID = '".session_id()."'";$resultCheck = mysql_db_query($dbname,$sqlCheck);if (!mysql_num_rows($resultCheck)) {	// Create new entry	$sql = "INSERT into transVisitorStats (			SID,			LandingPage,			UserAgent,			Refer,			DateVisit			) values (			'".session_id()."',			'".$pathInfo[basename]."',			'".$_SERVER[HTTP_USER_AGENT]."',			'".$_SERVER[HTTP_REFERER]."',			'".date("Y-m-d")."'			)";	$result = mysql_db_query($dbname,$sql);}
*/
// Open popup windowfunction popup($page,$width,$height,$toolbar,$status,$scrollbars,$class,$title) {	echo "<A HREF=\"javascript:NewWindow=window.open('$page','NewWindow','toolbar=$toolbar,status=$status,scrollbars=$scrollbars,width=$width,height=$height'); NewWindow.focus();\" class=\"$class\" title=\"$title\">";			}
// Check fieldsfunction fieldToDB($string) {	// Check for HTML characters	$string = stripslashes(htmlentities($string, ENT_QUOTES));	// Prevent SQL injection	$string = mysql_real_escape_string($string);		// Insert line breaks if needed	$string = str_replace('\r\n', '<br />', $string);	return $string;}
function DBToField($string) {	// Insert line breaks	$string = str_replace('<br />', '\r\n', $string);	// Replace bad characters with HTML	$string = html_entity_decode($string, ENT_QUOTES);	$string = stripslashes($string);	return $string;}
$browser = strstr(getenv('HTTP_USER_AGENT'), 'MSIE');
if (!empty($browser)) {
	// Check for Opera browser
	$opera = strstr(getenv('HTTP_USER_AGENT'), 'Opera');
	if (!empty($opera)) {
		$browser = "NS"; 
		$stylesheet = "layoutns.css";
		$jpeg_mime_type = "image/jpeg";
	} else {
		$browser = "IE"; 
		$stylesheet = "layoutie.css";
		$jpeg_mime_type = "image/pjpeg";
	}	
} else {
	$browser = "NS"; 
	$stylesheet = "layoutns.css";
	$jpeg_mime_type = "image/jpeg";
}

// Check Page --------------------------------------------- //
$selfArray = explode("/", $_SERVER[PHP_SELF]);
$elements = count($selfArray);
$last_element = $elements - 1;
$file = $selfArray[$last_element];
// Better mail function
function mailNew($fromName, $fromAddress, $to, $subject, $message) {
   // Copyright ? 2005 ECRIA LLC, http://www.ECRIA.com
   // Please use or modify for any purpose but leave this notice unchanged.
   $headers  = "MIME-Version: 1.0\n";
   $headers .= "Content-type: text/plain; charset=iso-8859-1\n";
   $headers .= "X-Priority: 3\n";
   $headers .= "X-MSMail-Priority: Normal\n";
   $headers .= "X-Mailer: php\n";
   $headers .= "From: \"".$fromName."\" <".$fromAddress.">\n";
   return mail($to,$subject,$message,$headers);
}

// Function to prevent email form injection attacks
function emailPreventInjection($input) {
	$repl = '';
	$input = (ereg_replace("\r", $repl, $input));
	$input = (ereg_replace("\n", $repl, $input));
	$input = (ereg_replace("%0a", $repl, $input));
	$input = (ereg_replace("%0d", $repl, $input));
	$input = (ereg_replace("Content-Type:", $repl, $input));
	$input = (ereg_replace("bcc:", $repl, $input));
	$input = (ereg_replace("to:", $repl, $input));
	$input = (ereg_replace("cc:", $repl, $input));
	return $input;
} 

function random_string($length) {
	global $string;
	// Generate Random Password
	mt_srand ((double) microtime() * 1000000);
	$possible = "ABCDEFGHJKLMNPQRSTUVWXYZ";
	$string = "";
	
	while (strlen($string) < $length) {
		$no_add = 0;
		$str = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
		// Check that preceeding character in $password is not same as current character
				
		if (strlen($string) >= 1) {
			for ($a=1;$a<=strlen($string);$a++) {
				// $str will be current character
				if ($str == substr("$string", -$a, 1)) { $no_add = 1; }
			} // End For Loop
		} // End If
		
		if ($no_add == 1) { continue; }
		$string .= $str; // Build the password string
	} // End While loop
	return $string;
}
// Function Resize_image()
// This function accepts a jpeg image, resizes it according to a scaling factor
// and then copies it to a new file with a specified filename "extension"
// Ex. resize_image(image.jpg, 100, thumb) 
// This would generate a new JPEG file called thumb_image.jpg at 100 pixels wide

function resize_image($orig_file,$max_width,$max_height,$file_ext,$dir,$border,$mime) {
	// Determine filenames
	$fileArray = explode("/", $orig_file);
	$file_elements = count($fileArray);
	$last_element = $file_elements - 1;
	if (!empty($file_ext)) {
		$out_file = $file_ext."_".$fileArray[$last_element];
	} else {
		$out_file = $fileArray[$last_element];
	}	
	
	// Rebuild directory string for thumbnail file
	$directory = "";
	for ($a=0;$a<=($last_element - 1);$a++) {
		if (empty($directory)) {
			$directory = $fileArray[$a];
		} else {
			$directory = $directory."/".$fileArray[$a];
		}		
	}
	if (!empty($dir)) { $directory = $directory."/".$dir; }
	
	$out_file = $directory."/".$out_file;	
		
	$size = getimagesize($orig_file);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		$im_in = imagecreatefromjpeg($orig_file);
	} elseif ($mime == "image/gif") {
		$im_in = imagecreatefromgif($orig_file);
	} elseif ($mime == "image/png") {
		$im_in = imagecreatefrompng($orig_file);
	}
	
	// Get original image dimentions
	$origW = $size[0];
	$origH = $size[1];
	
	// Get scale %age - we have 3 cases here
	if (!empty($max_width) && !empty($max_height)) {
		// This is gonna be tricky 'cause we want to avoid disportion
		// Do short side first, then figure out other dimention
		if ($origW > $origH) {
			// Horizontal orientation
			// Determine ideal scale
			$scale = floor($max_height / $origH);
			$new_height = $max_height;
			$new_width = $max_width;
			
			$optW = floor($origW*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origH;
				$cropH = $origH;							
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}		
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($orig_file);
			}						
				
		} elseif ($origW < $origH) {
			// Vertical orientation
			// Determine ideal scale
			$scale = floor($max_width / $origW);
			$new_width = $max_width;
			$new_height = $max_height;
			
			$optH = floor($origH*$scale);
			
			// Now we need to first crop image to the right proportions before scaling
			if ($max_width == $max_height) {
				$cropW = $origW;
				$cropH = $origW;							
				$origW = $cropW;
				$origH = $cropH;			
			} elseif ($max_width < $max_height) {
				$ratio = $max_width/$max_height;
				$cropW = ($origW*$ratio);
				$cropH = $origH;
				$origW = $cropW;
				$origH = $cropH;
			} elseif ($max_width > $max_height) {
				$ratio = $max_height/$max_width;
				$cropW = $origW;
				$cropH = ($origH*$ratio);
				$origW = $cropW;
				$origH = $cropH;
			}			
			$im_out = imagecreatetruecolor($cropW, $cropH);
			imagecopy($im_out, $im_in, 0, 0, 0, 0, $cropW, $cropH);
			if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
				imagejpeg($im_out, $out_file, 100);
				$im_in = imagecreatefromjpeg($out_file);
			} elseif ($mime == "image/gif") {
				imagegif($im_out, $out_file, 100);
				$im_in = imagecreatefromgif($out_file);
			} elseif ($mime == "image/png") {
				imagepng($im_out, $out_file, 100);
				$im_in = imagecreatefrompng($out_file);
			}			
		} elseif ($origW == $origH) {
			// Square - easy
			$new_width = $max_width;
			$new_height = $max_height;
		}
	} elseif (!empty($max_width) && empty($max_height)) {	
		$scale = ($max_width / $origW);
		$new_width = $max_width;
		$new_height = floor($origH * $scale);
	} elseif (!empty($max_height) && empty($max_width)) {
		$scale = ($max_height / $origH);
		$new_height = $max_height;
		$new_width = floor($origW * $scale);
	}
		
	$im_out = imagecreatetruecolor($new_width, $new_height);
	imagecopyresized($im_out, $im_in, 0, 0, 0, 0, $new_width, $new_height, $origW, $origH);
	if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
		imagejpeg($im_out, $out_file, 100);
	} elseif ($mime == "image/gif") {
		imagegif($im_out, $out_file, 100);
	} elseif ($mime == "image/png") {
		imagepng($im_out, $out_file, 100);
	}
	
	// Draw border
	if (!empty($border)) {
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			$im_in =  imagecreatefromjpeg($out_file);
		} elseif ($mime == "image/gif") {
			$im_in =  imagecreatefromgif($out_file);
		} elseif ($mime == "image/png") {
			$im_in =  imagecreatefrompng($out_file);
		}
		$color = ImageColorAllocate($im_in,0,0,0);
		ImageLine($im_in,0,0,($max_width-1),0,$color); // Top
		ImageLine($im_in,($max_width-1),1,($max_width-1),($max_height-1),$color); // Right
		ImageLine($im_in,($max_width-1),($max_height-1),1,($max_height-1),$color); // Bottom
		ImageLine($im_in,0,($max_height-1),0,0,$color); // Left
		if (($mime == "image/jpeg") || ($mime == "image/pjpeg")) {
			imagejpeg($im_in, $out_file, 100);
		} elseif ($mime == "image/gif") {
			imagegif($im_in, $out_file, 100);
		} elseif ($mime == "image/png") {
			imagepng($im_in, $out_file, 100);
		}
	}
	
	imagedestroy($im_out);
	imagedestroy($im_in);	
}

function replace_bad_chars($string) {
	global $new_string;
	$string = stripslashes($string);
	$new_string = $string;
	$badArray = array(Chr(47),Chr(34),Chr(35),Chr(39),Chr(32),Chr(92));
	$goodArray = array('','','','','_','');
	$elements = count($badArray);
	for($a=0;$a<=($elements-1);$a++) {
		$pat = $badArray[$a];
		$repl = $goodArray[$a];
		$new_string = (ereg_replace($pat, $repl, $new_string));
	}	
	return $new_string;
}

function daysBetweenDates($dateStart,$dateEnd) {
	global $days;
	$dateStartArray = explode("-",$dateStart);
	$dateEndArray = explode("-",$dateEnd);
	
	$startYear = $dateStartArray[0];
	$startMonth = $dateStartArray[1];
	$startDay = $dateStartArray[2];
	
	$endYear = $dateEndArray[0];
	$endMonth = $dateEndArray[1];
	$endDay = $dateEndArray[2];
	
	//first convert to unix timestamp
	$init_date = mktime(12,0,0,$startMonth,$startDay,$startYear);
	$dst_date = mktime(12,0,0,$endMonth,$endDay,$endYear);

	$offset = $dst_date-$init_date; //Depending on which offset type you want, switch order

	$days = floor($offset/60/60/24); 
	return $days;
}

function shortText($textToShorten,$noOfWords) {
	// shortText takes a string, parses on the spaces	// and returns noOfWords.	$stringArray = explode(' ',$textToShorten);	$words = count($stringArray);	if ($words<$noOfWords) {		return $textToShorten;		} else {		$returnString = '';		for($a=0;$a<($noOfWords-1);$a++) {			$returnString .= $stringArray[$a].' ';		}		// Trim trailing space		$returnString = trim($returnString).'...';		return $returnString;	}}
/*
function shortText($text,$words) {
	$text = strip_tags($text,'<a>');
	$textArray = explode(" ", $text);
	
	$noOfWords = count($textArray);

	if ($noOfWords<$words) {
		return $text;
	} else {
		$newText = null;
		for($zz=0;$zz<=($words);$zz++) {
			$newText .= $textArray[$zz]." ";
		}
		$shortText = $newText."...";
		
		return $shortText;
	}	
}
*/
/*
function shortText($text,$words) {
	global $shortText;
	$text = strip_tags($text,'<a>');
	$textArray = explode(" ", $text);
	$newText = null;
	for($zz=0;$zz<=($words);$zz++) {
		$newText .= $textArray[$zz]." ";
	}
	$shortText = $newText."...";
	
	return $shortText;
}
*/

function paginate($pages,$perPage,$urlString,$page,$pageNoOnly) {
	if (empty($page) || ($page == 0) ) { $page = 1;	}
	if (!empty($urlString)) { $urlString = "&".$urlString; }
	if ($pageNoOnly == 1) {
		echo "Page: ";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"".$_SERVER[PHP_SELF]."?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
	} else {
		echo "<div class=\"grayField\" style=\"text-align: right;\">Page: \n";
		for($p=1;$p<=$pages;$p++) {
			if ($p>1) { $start = ($p-1)*$perPage; }
			else { $start = 0; }
			if ($page == $p) { echo "<span class=orange><b>$p</b></span>\n"; }
			else { echo "<a href=\"".$_SERVER[PHP_SELF]."?page=$p&start=$start".$urlString."\"><b>$p</b></a>\n"; }
			if ($p < $pages) { echo " <font color=#c0c0c0>|</font> \n"; }
		}
		echo "</div>\n";
	}	
}

function microtime_float() {
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

// Hover grabs some text from the database based on ID and displays
// content in mouseover popup using overLib javaScript library.
function hoverHelp($type='',$helpID) {
	global $linkHelp, $dbname, $db, $db_selected;
	
	// Get content from ss_help
	$sql = "SELECT * from ss_help WHERE HID = '$helpID'";
	$result = mysql_db_query($dbname,$sql);
	$rowHelp = mysql_fetch_assoc($result);
	
	$helpTitle = stripslashes($rowHelp[BriefDesc]);
	$helpText  = stripslashes($rowHelp[HelpText]);
	
	$helpText = "<b>$helpTitle</b><br>$helpText";
	
	$linkHelp = null;
	$linkHelp .= "<img src=\"images/help.png\" border=\"0\" style=\"cursor: help;\" onmouseover=\"return overlib('$helpText', STICKY, CENTER, MOUSEOFF, WRAP, CELLPAD, 5);\" onmouseout=\"return nd();\">";
	return $linkHelp;
}
function hoverProfile($uID) {
	global $linkProfile, $dbname, $db, $db_selected;
	$monthArray = array('0','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec');
	
	// Get user profile settings : we've already determined if profile is visible
	// before getting to this function. NO WE HAVEN'T! CHECK IT NOW!
	$sql = "SELECT ShowProfile from ss_userSettings WHERE UID = '$uID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);	
	
	$sql = "SELECT * from ss_users WHERE UserID = '$uID'";
	$result = mysql_db_query($dbname,$sql);
	$rowProfile = mysql_fetch_assoc($result);
	
	if ($row[ShowProfile] == 1) {
		
		$userName   = $rowProfile[FirstName]." ".$rowProfile[LastName];
		$userImage  = $rowProfile[PhotoFile];
		if (!empty($rowProfile[PhotoFile])) {
			$userImage  = "users/".$rowProfile[FileDir]."/thumb_".$rowProfile[PhotoFile];
		} else {
			$userImage  = "images/user_no_photo.gif";
		}		
		$userHandle  = $rowProfile[Handle];
		$userLoc     = $rowProfile[Location];
		$userCountry = $rowProfile[Country]; 
		$userURL     = $rowProfile[URL];
		if (!empty($userHandle)) { $userLinkName = $userHandle; }
		else { $userLinkName = $userName; }
		
		$userIMICQ     = $rowProfile[IMICQ];
		$userIMMSN     = $rowProfile[IMMSN];
		$userIMAIM     = $rowProfile[IMAIM];
		$userIMYahoo   = $rowProfile[IMYahoo];
		
		$userBMonth    = $rowProfile[BirthMonth];
		$userBDay      = $rowProfile[BirthDay];
		
		$linkProfile = "<table border=0><tr><td valign=top><img src=$userImage title=$userName></td>";
		$linkProfile .= "<td valign=top><b>$userName</b><br>";
		if (!empty($userHandle)) { $linkProfile .= "$userHandle<br>"; }
		if (!empty($userLoc)) { $linkProfile .= "$userLoc<br>"; }
		if (!empty($userCountry)) { $linkProfile .= "$userCountry<br>"; }
		
		$linkProfile .= "</td></tr></table>";
		
		if (!empty($userURL)) { $linkProfile .= "<a href=$userURL target=_blank>$userURL</a><br>"; }
		if (!empty($userIMICQ)) { $linkProfile .= "ICQ Number: $userIMICQ<br>"; }
		if (!empty($userIMMSN)) { $linkProfile .= "MSN Handle: $userIMMSN<br>"; }
		if (!empty($userIMAIM)) { $linkProfile .= "AIM Screen Name: $userIMAIM<br>"; }
		if (!empty($userIMYahoo)) { $linkProfile .= "Yahoo! Handle: $userIMYahoo<br>"; }
		if (!empty($userBMonth) && !empty($userBDay)) { $linkProfile .= "Birthday: ".$monthArray[$userBMonth]." $userBDay<br>"; }
		
		$linkProfile .= "<br><div align=right><a href=myShop_userProfile.php?uID=$uID><b>View full profile for $userName</b></a> <font color=red><b>&raquo;</b></font></div>";
		
		$linkProfile = "<a href=\"#\" onmouseover=\"return overlib('$linkProfile', STICKY, CENTER, MOUSEOFF, WRAP, CELLPAD, 5);\" onmouseout=\"return nd();\">\n";
		$linkProfile .= "$userLinkName</a>";
	} else {
		$linkProfile = " &nbsp;".$rowProfile[FirstName]." ".$rowProfile[LastName];
	}
	return $linkProfile;
}

// resourceStats displays the Comments,Downloads,Views icons
// in file listResources.php
function resourceStats($rID,$rLink) {
	global $statString, $dbname, $db, $db_selected;
	// Get resource stats
	$sql = "SELECT Views,Downloads from ss_resource WHERE ID = '$rID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$views = $row[Views];
	$downloads = $row[Downloads];
	
	$sql = "SELECT ID from ss_resourcePost WHERE RID = '$rID'";
	$result = mysql_db_query($dbname,$sql);
	$comments = mysql_num_rows($result);
	
	$statString  = "<a href=\"http://www.sonixshop.com/".$rLink."\" title=\"$comments Comments\"><img src=\"images/icon_word_baloon_small.gif\" border=\"0\"></a> <span class=smallGray>$comments</span>&nbsp;\n";
	$statString .= "<a href=\"http://www.sonixshop.com/".$rLink."\" title=\"$downloads Downloads\"><img src=\"images/icon_small_downloads.gif\" border=\"0\"></a> <span class=smallGray>$downloads</span>&nbsp;\n";
	$statString .= "<a href=\"http://www.sonixshop.com/".$rLink."\" title=\"$views Views\"><img src=\"images/icon_small_view.png\" border=\"0\"></a> <span class=smallGray>$views</span>&nbsp;\n";
	
	return $statString;
}

// adCodeGrabber gets random ad code for a specified ad zone
// ZONES:
//	1. Header
//	2. Right Column
//	3. Bottom of page
//	4. Below Main Menu on Left
function adCodeGrabber($zone) {
	global $codeString, $dbname, $db, $db_selected;
	
	// Get all adCodeID's for this zone
	$sql = "SELECT CodeID from ss_adCode WHERE AdZone = '$zone' AND Active = '1'";
	$result = mysql_db_query($dbname,$sql);
	$i=0;
	while ($value = mysql_fetch_assoc($result)) {
		$codeIDArray[$i] = $value[CodeID];
		$i++;
	}
	$codes = count($codeIDArray);
	
	// Get random codeID
	srand((double)microtime()*1000000);
	$randomCodeID = rand(1,($codes));
	$randomCodeID = $codeIDArray[$randomCodeID-1];
	
	// Get ad code
	$sql = "SELECT AdCode from ss_adCode WHERE CodeID = '$randomCodeID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$codeString = $row[AdCode];
	
	return $codeString;
}

// Mail Jeff sends Jeff an email at critical points: 
// registration, contact, feature request, link to us, etc.
function mailAdmin($fromWhere,$name,$email,$title=null,$url=null) {
	global $masterMail;
	if (empty($name)) { $name = "Joe User"; }
	if (empty($email)) { $email = "info@tcnTransition.org"; }
	
	if ($fromWhere == "registration") {
		$subject     = "soniXshop Registration";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has become a soniXshop member.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	} elseif ($fromWhere == "contact") {
		$subject     = "TCN Contact Form";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has contacted the Transition Community Network by email. To view this message, please follow this link and log in to your admin account:
http://www.tcnTransition.org/admin";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);	
	} elseif ($fromWhere == "feature") {
		$subject     = "soniXshop Feature Request";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has submitted a soniXshop Feature Request.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	} elseif ($fromWhere == "link") {
		$subject     = "soniXshop Link to Us";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has downloaded a soniXshop Link Banner.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	} elseif ($fromWhere == "newResource") {
		$subject     = "New Resource Added";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has posted a new resource.\n\n";
		$message    .= "$title\n$url\n\n";
		$message    .= "This resource has not been approved and activated so it will not appear on the website.\n";
		$message    .= "Log into your admin account to approve this resource.\n";
		$message    .= "http://www.tcnTransition.org/admin";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);		
	} elseif ($fromWhere == "emailFriend") {
		$subject     = "soniXshop Email Resource to Friend";
		$fromName    = $name;
		$fromAddress = $email;
		$to          = $masterMail;
		$message     = "$name has emailed a resource to a friend.";		
		mailNew($fromName, $fromAddress, $to, $subject, $message);
	}
}

function deleteProject($pID) {
	global $dbname, $db, $db_selected;

	// This function deletes everything associated with a project
	
	// 1.  Delete main project record
	$sql = "DELETE from ss_project WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 2.  Delete project calculation records
	$sql = "DELETE from ss_projectCalc WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 3. Delete project part records
	$sql = "DELETE from ss_projectParts WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 4. Delete project parts name record
	$sql = "DELETE from ss_projectPartsName WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 5. Delete project resource entries
	$sql = "DELETE from ss_projectResource WHERE PID = '$pID'";
	$result = mysql_db_query($dbname,$sql);	
}

function deletePartsList($plID) {
	global $dbname, $db, $db_selected;

	// This function deletes everything associated with a parts list	
	// 1. Delete project part records
	$sql = "DELETE from ss_projectParts WHERE LID = '$plID'";
	$result = mysql_db_query($dbname,$sql);
	
	// 2. Delete project parts name record
	$sql = "DELETE from ss_projectPartsName WHERE ID = '$plID'";
	$result = mysql_db_query($dbname,$sql);
}

function buildBreadcrumbs($path) {	global $subSubCatName, $breadCrumbs, $dbname, $db, $db_selected;	// $path is in the form of /mainCat/subCat/subSubCat		$pathArray = explode('/',$path);	$mainCat   = $pathArray[1];	$subCat    = $pathArray[2];	$subSubCat = $pathArray[3];
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat'";	$result = mysql_db_query($dbname,$sql);	$row = mysql_fetch_assoc($result);	$mainCatName = stripslashes($row[LevelName]);
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat'";	$result = mysql_db_query($dbname,$sql);	$row = mysql_fetch_assoc($result);	$subCatName = stripslashes($row[LevelName]);
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat/$subSubCat'";	$result = mysql_db_query($dbname,$sql);	$row = mysql_fetch_assoc($result);	$subSubCatName = stripslashes($row[LevelName]);
	//$breadCrumbs = "<a href=\"$siteURL/$mainCat\" class=\"orangeLink\">$mainCatName</a> :\n";	//$breadCrumbs .= "<a href=\"$siteURL/$mainCat/$subCat\" class=\"orangeLink\">$subCatName</a>\n";	//$breadCrumbs .= "<a href=\"$siteURL/$mainCat/$subCatName/$subSubCat\" class=\"orangeLink\">$subSubCatName</a>\n";
	$breadCrumbs = '<a href="'.$siteURL.'resourceProcess.php?c=/'.$mainCat.'" class="orangeLink">'.$mainCatName.'</a> :';
	$breadCrumbs .= '<a href="'.$siteURL.'resourceProcess.php?c=/'.$mainCat.'/'.$subCat.'" class="orangeLink">'.$subCatName.'</a>';
	
	return $subSubCatName;	return $breadCrumbs;}
function buildBreadcrumbs2($path) {	global $breadCrumbs, $dbname, $db, $db_selected;	// $path is in the form of /mainCat/subCat/subSubCat
	$pathArray = explode('/',$path);	$mainCat   = $pathArray[1];	$subCat    = $pathArray[2];	$subSubCat = $pathArray[3];
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat'";	$result = mysql_db_query($dbname,$sql);	$row = mysql_fetch_assoc($result);	$mainCatName = stripslashes($row[LevelName]);
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat'";	$result = mysql_db_query($dbname,$sql);	$row = mysql_fetch_assoc($result);	$subCatName = stripslashes($row[LevelName]);
	$sql = "SELECT * from transLevels WHERE Path = '/$mainCat/$subCat/$subSubCat'";	$result = mysql_db_query($dbname,$sql);	$row = mysql_fetch_assoc($result);	$subSubCatName = stripslashes($row[LevelName]);
	if (empty($mainCatName) && empty($subCatName) && empty($subSubCatName)) {		$breadCrumbs = '';	} else {		$breadCrumbs = '';		if (!empty($mainCatName)) {			$breadCrumbs .= $mainCatName.' ';		} 		if (!empty($subCatName)) {			$breadCrumbs .= ': '.$subCatName.' ';		}		if (!empty($subSubCatName)) {			$breadCrumbs .= ': '.$subSubCatName;		}	}	return $breadCrumbs;}
function badLink($linkID=null,$statusCode=null) {	global $breadCrumbs, $dbname, $db, $db_selected;	if (!empty($linkID)) {		if (empty($statusCode)) {			$statusCode = 'userbl';		}		$sql = "UPDATE transLinks SET 					ErrorCode = '$statusCode',					ErrorLevel = '1',					ErrorDate = '".date('Y-m-d')."'					WHERE					LinkID = '$linkID'";		$result = mysql_db_query($dbname,$sql);		// Get info for email notification		$sql = "SELECT Title,Link from transLinks WHERE LinkID = '$linkID'";		$result = mysql_db_query($dbname,$sql);		$row = mysql_fetch_assoc($result);
		$title = stripslashes($row[Title]);					$url   = $row[Link];
		// Get path information		$sql = "SELECT TL.Path from transLevels TL				LEFT JOIN transLinkPath TLP ON TLP.PathID = TL.LevelID				WHERE TLP.LinkID = '$linkID'";		$result = mysql_db_query($dbname,$sql);		$row = mysql_fetch_assoc($result);		$path = $row[Path];		$fullPath = buildBreadcrumbs2($path);
		$fromName    = MASTER_FROM;		$fromAddress = MASTER_MAIL;				$subject = 'Broken link notification: '.$title;		$message = 'A broken link notification has been sent by a TCN user. See details below...----------------------------------------------------------------------------Title:  '.$title.'URL:    '.$url.'Path:   '.$fullPath.'Where to find:  http://www.tcntransition.org'.$path;
		// Send notification to webmaster		$to = EMAIL_WEBMASTER;				mailNew($fromName, $fromAddress, $to, $subject, $message);
		// Send notification to site owner		$to = EMAIL_SITE_OWNER;				mailNew($fromName, $fromAddress, $to, $subject, $message);
		// Send notification to Andrea		$to = EMAIL_ASSISTANT1;				mailNew($fromName, $fromAddress, $to, $subject, $message);	}		return $linkID;}
function linkChecker($url) {	global $html;
	$linkInfo  = @parse_url( $url );	$fp = fsockopen( $linkInfo["host"], 80, $errno, $errstr, 10 );	if ( !$fp ) {		return false;	} else {		if( empty( $linkInfo["path"] ) ) {	        // If it is empty it fills it	        $linkInfo["path"] = "/";	     }	     $query = "";
	     // Checks if there is a query string in the url	     if( isset( $linkInfo["query"] ) ) {	          // If there is a query string it adds a ? to the front of it	          $query = "?".$linkInfo["query"]."";	     }
	     // Sets the headers to send	     $out  = "HEAD ".$linkInfo["path"]."".$query." HTTP/1.0\r\n";	     $out .= "Host: ".$linkInfo["host"]."\r\n";	     $out .= "Connection: close \r\n" ;	     $out .= "User-Agent: link_checker/1.1\r\n\r\n";
	     // writes the headers out	     @fwrite( $fp, $out );	     $html = '';
	     // Reads what gets sent back	     while ( !@feof( $fp ) ) {	          $html .= @fread( $fp, 8192 );	     }	     // Closes socket	     @fclose( $fp );	 }    	 return $html;	}
function getstatuscode( $header ) {	global $status;  // Splits the headers into an array  $headers = explode( "\r\n", $header );  unset( $header );  for( $i=0;isset( $headers[$i] );$i++ ) {
    // Checks if the header is the status header    if( preg_match( "/HTTP\/[0-9A-Za-z +]/i" ,$headers[$i] ) ) {      // If it is save the status      $status = preg_replace( "/http\/[0-9]\.[0-9]/i","",$headers[$i] );    }  }  return $status;}
// convertDateTime takes a MySQL DateTime field in form of// YYYY-MM-DD HH:MM:SS and converts it to Jan 1, 2007 7:05am// Remember: 00:00:00 = 12:00am, 23:59:59 = 11:59:59pmfunction convertDateTime($dateTime) {	global $returnArray,$convertedDate;
	$dateTimeArray = explode(' ',$dateTime);	$date = $dateTimeArray[0];	$time = $dateTimeArray[1];	$timeArray = explode(':',$time);	$hour = $timeArray[0];	$min  = $timeArray[1];	$sec  = $timeArray[2];
	// Assumption: if 00:00:00, let's assume no time was entered	if ( ($hour=='00') && ($min=='00') && ($sec=='00') ) { $newTime = ''; }	else {			if ($hour>11) { $ampm = 'pm'; }			else { $ampm = 'am'; }						if (substr($hour,0,1)==0) { $hour = substr($hour,1,1); }						if ($hour>12) { $hour = $hour-12; }								$newTime = $hour.':'.$min.$ampm;	}			if ( !empty($date) && ($date != '0000-00-00') ) {		$newDate = mysql_to_date2($date);	} else {		$newDate = '';	}		$returnArray = array($newDate,$newTime);	return $returnArray;		}

function getFileList($catID,$subCatID) {
	global $dbname, $db, $db_selected;
	$sql = "SELECT * from transSharedFiles 
				WHERE 
				CatID = '$catID' AND 
				SubCatID = '$subCatID' AND
				Approved = 1
				ORDER BY FileTitle DESC"; 	
	$result = mysql_db_query($dbname,$sql); 
	$fileString = '';
			
	if (mysql_num_rows($result)>0) {
		while ($value = mysql_fetch_assoc($result)) {
			$fileName = $value['FileName'];
			$fileTitle = stripslashes($value['FileTitle']);
			$fileDesc  = stripslashes($value['FileDesc']);
			$fileDate  = $value['FileDate'];
			$fileType  = $value['FileType'];
			
			switch ($fileType) {
				case 'application/pdf':
				    $mimeClass = 'mimePDF';
				    break;
				case 'application/msword':
				    $mimeClass = 'mimeWord';
				    break;
				case 'text/comma-separated-values':
				    $mimeClass = 'mimeExcel';
				    break;
				case 'application/vnd.ms-excel':
				    $mimeClass = 'mimeExcel';
				    break;    
				default:
    				$mimeClass = 'mimeDefault';
			}
			$filePath = 'docs/District Documents/'.$fileName;
			
			$fileString .= '<div class="mimeIconContainer '.$mimeClass.'">';
			$fileString .= '<a href="'.$filePath.'" target="_blank" title="Download '.$fileTitle.'">'.$fileTitle.'</a>';
			$fileString .= '&nbsp;&nbsp;<span class="smallGray">'.mysql_to_date2($fileDate).'</span>';
			$fileString .= '</div>';
		}
	} else {
		$fileString .= 'There are no files here right now. Please check back again later. Thanks!';	
	}
	return $fileString;
}?>